<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible"  width="1280">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
      enctype="multipart/form-data"
    >
      <el-row>
        <el-col :span="8">
          <el-form-item label="备货单号" prop="stockNo">
            <el-input v-model="formData.stockNo" placeholder="请输入备货单号" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="备货单名称" prop="stockName">
            <el-input v-model="formData.stockName" placeholder="请输入备货单名称" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="备货单类型" prop="stockType">
            <el-select v-model="formData.stockType" placeholder="请选择备货单类型 ">
              <el-option
                v-for="dict in getIntDictOptions(DICT_TYPE.CRM_STOCK_TYPE)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="客户名称" prop="customerId">
            <el-select
              filterable
              clearable
              v-model="formData.customerId"
              :disabled="formData.customerDefault"
              @change="onChangeCustomer($event)"
              placeholder="请选择客户"
              class="w-1/1"
            >
              <el-option
                v-for="item in customerList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="店铺名称" prop="storeId">
            <el-select
              filterable
              clearable
              v-model="formData.storeId"
              @change="onChangeStore($event)"
              placeholder="请选择店铺"
              class="w-1/1"
            >
              <el-option
                filterable
                clearable
                v-for="item in getStoreOptions"
                :key="item.id"
                :label="item.storeName"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="品牌名称" prop="brandId">
            <el-select
              filterable
              clearable
              v-model="formData.brandId"
              placeholder="请选择品牌"
              class="w-1/1"
            >
              <el-option
                filterable
                clearable
                v-for="item in getBrandOptions"
                :key="item.id"
                :label="item.brandName"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="项目名称" prop="projectName">
            <el-input v-model="formData.projectName" placeholder="请输入项目名称" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="备货单状态" prop="stockStatus">
            <el-select v-model="formData.stockStatus" placeholder="请选择备货单状态">
              <el-option
                v-for="dict in getIntDictOptions(DICT_TYPE.CRM_STOCK_STATUS)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="制单人" prop="signUserId">
            <el-select
              filterable
              clearable
              v-model="formData.signUserId"
              class="w-1/1"
            >
              <el-option
                v-for="item in userOptions"
                :key="item.id"
                :label="item.nickname"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="下单部门" prop="deptId">
            <el-tree-select
              filterable
              clearable
              v-model="formData.deptId"
              class="w-1/1"
              :data="deptList"
              :props="defaultProps"
              check-strictly
              node-key="id"
              placeholder="请选择下单部门"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="完成时间" prop="finishTime">
            <el-date-picker
              v-model="formData.finishTime"
              type="date"
              value-format="x"
              :formatter="dateFormatter"
              placeholder="选择完成时间"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="备货单文件" prop="file">
            <el-upload
              ref="uploadRef"
              v-model:file-list="fileList"
              :disabled="formLoading"
              :on-exceed="handleExceed"
              :on-remove="handleRemove"
              :auto-upload="false"
              :limit="1"
              :show-file-list="true"
              accept=".xlsx, .xls"
              action="none"
              drag
            >
              <Icon icon="ep:upload" />
              <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
              <template #tip>
                <div class="el-upload__tip text-center">
                  <span>仅允许导入 xls、xlsx 格式文件。</span>
                  <el-link
                    :underline="false"
                    style="font-size: 12px; vertical-align: baseline"
                    type="primary"
                    @click="importTemplate"
                  > 下载模板
                  </el-link>
                </div>
              </template>
            </el-upload>
          </el-form-item>
        </el-col>
        <el-col :span="12" >
          <el-form-item label="备注说明" prop="description" >
            <el-input type="textarea" v-model="formData.note" placeholder="请输入产品简介" :rows="5" maxlength="120"/>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading" v-show="showFlag">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
// 1引入组件
import XLSX from 'xlsx'
import { dateFormatter } from '@/utils/formatTime'
import { StockProductApi, StockProduct } from '@/api/crm/stockproduct'
import {StoreApi} from "@/api/crm/store";
import {BrandApi} from "@/api/crm/brand";
import * as CustomerApi from "@/api/crm/customer";
import * as UserApi from "@/api/system/user";
import {useUserStore} from "@/store/modules/user";
import download from "@/utils/download";
import { defaultProps, handleTree } from '@/utils/tree'
import * as DeptApi from "@/api/system/dept";
import {UploadUserFile} from "element-plus";
import {Dayjs} from "dayjs";
import * as ContractApi from "@/api/crm/contract";

/** CRM 备货单记录 表单 */
defineOptions({ name: 'StockProductForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const showFlag = ref(true) // 表单的加载中：提交的按钮隐藏
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const fileList = ref<UploadUserFile[]>([]) // 文件列表
const uploadRef = ref()
const formData = ref({
  id: undefined,
  stockNo: undefined,
  stockName: undefined,
  deptId: undefined,
  projectName: undefined,
  signUserId: undefined,
  finishTime: undefined,
  customerId: undefined,
  storeId: undefined,
  brandId: undefined,
  stockStatus: undefined,
  stockType: undefined,
  fileUrls: undefined,
  file: undefined,
  note: undefined,
})
const formRules = reactive({
  stockNo: [{ required: true, message: '备货单号不能为空', trigger: 'blur' }],
  // stockName: [{ required: true, message: '备货单名称不能为空', trigger: 'blur' }],
  // finishTime: [{ required: true, message: '完成时间不能为空', trigger: 'blur' }],
  // stockStatus: [{ required: true, message: '备货单状态不能为空', trigger: 'blur' }],
  // stockType: [{ required: true, message: '备货单类型不能为空', trigger: 'change' }],
  customerId: [{ required: true, message: '客户不能为空', trigger: 'change' }],
  // file: [{ required: true, message: '备货单文件不能为空', trigger: 'change' }],
})
const formRef = ref() // 表单 Ref
const customerList = ref([]) // 客户列表的数据
const storeList = ref([]) // 门店列表的数据
const brandList = ref([]) // 品牌列表的数据
const userOptions = ref<UserApi.UserVO[]>([]) // 用户列表
const deptList = ref<Tree[]>([]) // 部门树形结构

const tableHeaders = ref([]);  // 存储表头信息
const tableData = ref([]);  // 存储表格数据

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type

  resetForm()
  // 所属部门
  deptList.value = handleTree(await DeptApi.getSimpleDeptList())
  // 获得用户列表
  userOptions.value = await UserApi.getSimpleUserList()
  // 默认新建时选中自己
  if (formType.value === 'create') {
    formData.value.signUserId = useUserStore().getUser.id
    formData.value.deptId = useUserStore().getUser.deptId
  }
  // 获得客户、门店、品牌下拉选列表
  customerList.value = await CustomerApi.getCustomerSimpleList()
  storeList.value = await StoreApi.getStoreSimpleList()
  brandList.value = await BrandApi.getBrandSimpleList()

  // 修改时，设置数据
  if (id) {
    if("detail"===type){
      showFlag.value = false
    }
    formLoading.value = true
    try {
      formData.value = await StockProductApi.getStockProduct(id)
    } finally {
      formLoading.value = false
    }
  }

}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = unref(formData.value) as unknown as StockProduct
    const uploadFormData = getUploadFormData()
    if (formType.value === 'create') {
      if (fileList.value.length == 0) {
        message.error('请上传备货单文件')
        return
      }
      // 将文件对象 file 添加到 formData 对象中，uploadFile 需要与后端接口中接收文件的参数名一致，如果不一致，则后端需要指定参数名，如 @RequestPart("uploadFile") MultipartFile file
      uploadFormData.append("file", fileList.value[0].raw as Blob);
      const res =  await StockProductApi.createStockProduct(uploadFormData) ;
      submitFormSuccess(res)
    }
    else {
      const uploadFormData = new FormData();
      // 将文件对象 file 添加到 formData 对象中，uploadFile 需要与后端接口中接收文件的参数名一致，如果不一致，则后端需要指定参数名，如 @RequestPart("uploadFile") MultipartFile file
      if (fileList.value.length > 0) {
        uploadFormData.append('file',  fileList.value[0].raw as Blob)
      }
      if(formData.value.id){
        uploadFormData.append("id", formData.value.id as string);
      }
      const res = await StockProductApi.updateStockProduct(uploadFormData)
      // res.formType = formType.value
      submitFormSuccess(res)
    }
  } finally {
    formLoading.value = false
  }
}
const getUploadFormData = () =>{
  const uploadFormData = new FormData();
  // 将普通对象 qualityFileObj 的属性添加到 uploadFormData 对象中
  if(formData.value.stockNo){
    uploadFormData.append("stockNo", formData.value.stockNo as string);
  }
  if(formData.value.stockName){
    uploadFormData.append("stockName", formData.value.stockName as string);
  }
  if(formData.value.deptId){
    uploadFormData.append("deptId", formData.value.deptId  as number);
  }
  if(formData.value.projectName){
    uploadFormData.append("projectName", formData.value.projectName as string);
  }
  if(formData.value.signUserId){
    uploadFormData.append("signUserId", formData.value.signUserId as number);
  }
  if(formData.value.finishTime){
    uploadFormData.append("finishTime", formattedDate(formData.value.finishTime) as Date);
  }
  if(formData.value.customerId){
    uploadFormData.append("customerId", formData.value.customerId as number);
  }
  if(formData.value.storeId){
    uploadFormData.append("storeId", formData.value.storeId as number);
  }
  if(formData.value.brandId){
    uploadFormData.append("brandId", formData.value.brandId as number);
  }
  if(formData.value.stockStatus){
    uploadFormData.append("stockStatus", formData.value.stockStatus as number);
  }
  if(formData.value.stockType){
    uploadFormData.append("stockType", formData.value.stockType as number);
  }
  if(formData.value.note){
    uploadFormData.append("note", formData.value.note as string);
  }

  return uploadFormData;
}
// 时间戳转换为yyyy-MM-dd HH:mm:ss
const formattedDate = (time: any) => {
  const date = new Date(time);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const second = String(date.getSeconds()).padStart(2, '0');

  return `${year}-${month}-${day} ${hours}:${minutes}:${second}`;
};

const submitFormSuccess = (response: any) => {
  if (response.code !== 0) {
    message.error(response.msg)
    formLoading.value = false
    return
  }
  const formType = response.formType
  const data = response.data
  let insertCount = data.createProductNames.length
  let updateCount = data.updateProductNames.length
  let errorCount = Object.keys(data.failureProductNames).length
  let text = ""
  if(formType === "update" && insertCount===0 && updateCount===0 && errorCount===0){
    // 更新返回结果，且未上传文件
    text = "更新成功"
  }else{
    // 拼接提示语
    text = '上传成功数量：' + insertCount + ';'
    for (let productName of data.createProductNames) {
      text += '< ' + productName + ' >'
    }
    text += '更新成功数量：' + updateCount + ';'
    for (const productName of data.updateProductNames) {
      text += '< ' + productName + ' >'
    }
    text += '失败数量：' + errorCount + ';'
    for (const msg in data.failureProductNames) {
      text += '< ' + msg + ': ' + data.failureProductNames[msg] + ' >'
    }
  }
  message.alert(text)
  if(insertCount>0 || updateCount>0 || errorCount<=0){
    formLoading.value = false
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  }else{
    formLoading.value = false
    return
  }


}

/** 上传错误提示 */
const submitFormError = (): void => {
  message.error('上传失败，请您重新上传！')
  formLoading.value = false
}

/** 重置表单 */
const resetForm = async () => {
  formData.value = {
    id: undefined,
    stockNo: undefined,
    stockName: undefined,
    deptId: undefined,
    projectName: undefined,
    signUserId: undefined,
    finishTime: undefined,
    customerId: undefined,
    storeId: undefined,
    brandId: undefined,
    stockStatus: undefined,
    stockType: undefined,
    fileUrls: undefined,
    file: undefined,
  }
  formRef.value?.resetFields()
  // 重置上传状态和文件
  fileList.value = []
  await nextTick()
  uploadRef.value?.clearFiles()
}

/** 动态获取门店 */
const getStoreOptions = computed(() =>{
    if( formData.value.customerId){
     return  storeList.value.filter((item) => item.customerId == formData.value.customerId)
    }else{
      return  storeList.value
    }
})
const getBrandOptions = computed(() =>{
    if( formData.value.customerId){
      return brandList.value.filter((item) => item.customerId == formData.value.customerId)
    }else{
      return  brandList.value
    }
})
/*店铺变更*/
const onChangeStore = (event) => {
  const selectedOptionObj = storeList.value.find(opt => opt.id === event); // 找到对应的对象
  formData.value.areaId = selectedOptionObj.areaId
  formData.value.detailAddress = selectedOptionObj.detailAddress
  // formRef.value?.resetFields()
}

/** 文件数超出提示 */
const handleExceed = (): void => {
  message.error('最多只能上传一个文件！')
}

/** 下载模板操作 */
const importTemplate = async () => {
  const res = await StockProductApi.importStockTemplate()
  download.excel(res, '备货单导入模版.xls')
}
//移除文件的操作方法
const handleRemove = (file) => {

}
const handleImport = (file) => {
  // 文件类型校验
  if(!/\.xlsx|\.xls$/.test(file.name)) {
    message.error("仅支持 Excel 文件");
    return;
  }

  const reader = new FileReader();
  reader.onload = (e) => {
    try {
      // 读取文件内容
      const data = new Uint8Array(e.target.result);
      const workbook = XLSX.read(data, { type: "array" });

      // 解析第一个工作表
      const firstSheetName = workbook.SheetNames[0];
      const worksheet = workbook.Sheets[firstSheetName];

      // 转换为二维数组 [[表头], [行数据]...]
      const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 });

      // 提取表头
      tableHeaders.value = jsonData[0];
      console.info(tableHeaders.value)
      // 构造对象数组
      tableData.value = jsonData.slice(1).map(row => {
        return tableHeaders.value.reduce((obj, header, index) => {
          obj[header] = row[index] || "";
          return obj;
        }, {});
      });

      message.success("导入成功");
    } catch (error) {
      message.error(`解析失败: ${error.message}`);
    }
  };

  // 以 ArrayBuffer 格式读取文件
  reader.readAsArrayBuffer(file.raw);
};

</script>
